package io.gitee.xyuesheng.day07;

import org.junit.Test;

import java.io.*;

public class TestReader {
    @Test
    public void test() {
//        try(InputStream in=new FileInputStream("data\\忧.txt")){
//            byte[] bytes=new byte[6];//两个字

//        try(InputStream in=new FileInputStream("data\\机.txt")){//乱码

//            int c=in.read();
//            System.out.println((char)c);//乱码

//            in.read(bytes);
//            System.out.println(new String(bytes));

        try (InputStream in = new FileInputStream("data\\中文.txt")) {
            byte[] bytes = new byte[4];
            in.read(bytes);
            System.out.println(new String(bytes, "GBK"));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //中文名的文件，打开的时候，需要使用gbk对文件名进行编码
//        String fileName =new String("机.txt".getBytes("gbk"));
//        System.out.println(new File(fileName).exists());//true
//        String fileName=new String("中文.txt".getBytes("utf-8"));
//        System.out.println(new File(fileName).exists());//false

    @Test
    public void test1() {
        /**
         * 文件编码是gbk
         * 1.如果代码的编码是gbk，文件可以正常读取
         * 2.如果代码是UTF-8，文件读取出错
         */
        //把文件存为“utf-8”
//        try(InputStream reader =new FileInputStream("data\\忧.txt")){
        try (InputStream reader = new FileInputStream("data\\机.txt")) {
            int c;

            while ((c = reader.read()) != -1) {
                System.out.print((char) c);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Test
    public void test2() {
        //使用指定的编码读取文件
        try (
                //构建字节流
                InputStream in = new FileInputStream("data\\中文.txt");
//                InputStream in =new FileInputStream("data\\chinese.txt");
                //使用指定的编码，把字节流转化成字符流
                InputStreamReader reader = new InputStreamReader(in, "GBK");
        ) {
            int c;

            while ((c = reader.read()) != -1) {
                System.out.print((char) c);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
